import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import './Settings.css';

interface AppSettings {
  theme: 'light' | 'dark' | 'system';
  thumbnailSize: 'small' | 'medium' | 'large';
  autoImport: boolean;
  duplicateHandling: 'skip' | 'rename' | 'replace';
  cacheSize: number;
  language: 'zh-CN' | 'en-US';
}

/**
 * 设置页面组件
 * 管理应用程序的各种设置选项
 */
export default function Settings() {
  const navigate = useNavigate();
  const [settings, setSettings] = useState<AppSettings>({
    theme: 'system',
    thumbnailSize: 'medium',
    autoImport: false,
    duplicateHandling: 'skip',
    cacheSize: 1024,
    language: 'zh-CN'
  });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [appInfo, setAppInfo] = useState<any>(null);

  useEffect(() => {
    loadSettings();
    loadAppInfo();
  }, []);

  /**
   * 加载设置
   */
  const loadSettings = async () => {
    try {
      setLoading(true);
      // TODO: 实现获取设置的 API
      // const savedSettings = await window.photosAPI.getSettings();
      // setSettings(savedSettings);
    } catch (error) {
      console.error('Failed to load settings:', error);
    } finally {
      setLoading(false);
    }
  };

  /**
   * 加载应用信息
   */
  const loadAppInfo = async () => {
    try {
      // TODO: 实现获取应用信息的 API
      // const info = await window.photosAPI.getAppInfo();
      // setAppInfo(info);
      
      // 临时模拟数据
      setAppInfo({
        name: 'Photos Plover Store',
        version: '1.0.0',
        platform: 'darwin',
        arch: 'arm64'
      });
    } catch (error) {
      console.error('Failed to load app info:', error);
    }
  };

  /**
   * 保存设置
   */
  const saveSettings = async () => {
    try {
      setSaving(true);
      // TODO: 实现保存设置的 API
      // await window.photosAPI.saveSettings(settings);
      
      // 显示成功消息
      await (window as any).photosAPI?.showMessageBox({
        type: 'info',
        title: '设置已保存',
        message: '设置已成功保存'
      });
    } catch (error) {
      console.error('Failed to save settings:', error);
      await (window as any).photosAPI?.showMessageBox({
        type: 'error',
        title: '保存失败',
        message: '保存设置时发生错误',
        detail: error instanceof Error ? error.message : '未知错误'
      });
    } finally {
      setSaving(false);
    }
  };

  /**
   * 重置设置
   */
  const resetSettings = async () => {
    try {
      const result = await (window as any).photosAPI?.showMessageBox({
        type: 'warning',
        title: '确认重置',
        message: '确定要重置所有设置吗？',
        detail: '此操作将恢复默认设置，不可撤销',
        buttons: ['取消', '重置'],
        defaultId: 0,
        cancelId: 0
      });

      if (result.response === 1) {
        const defaultSettings: AppSettings = {
          theme: 'system',
          thumbnailSize: 'medium',
          autoImport: false,
          duplicateHandling: 'skip',
          cacheSize: 1024,
          language: 'zh-CN'
        };
        setSettings(defaultSettings);
        await saveSettings();
      }
    } catch (error) {
      console.error('Failed to reset settings:', error);
    }
  };

  /**
   * 清理缓存
   */
  const clearCache = async () => {
    try {
      const result = await (window as any).photosAPI?.showMessageBox({
        type: 'warning',
        title: '确认清理',
        message: '确定要清理所有缓存吗？',
        detail: '这将删除所有缩略图缓存，下次浏览时需要重新生成',
        buttons: ['取消', '清理'],
        defaultId: 0,
        cancelId: 0
      });

      if (result.response === 1) {
        // TODO: 实现清理缓存的 API
        // await window.photosAPI.clearCache();
        
        await (window as any).photosAPI?.showMessageBox({
          type: 'info',
          title: '清理完成',
          message: '缓存已成功清理'
        });
      }
    } catch (error) {
      console.error('Failed to clear cache:', error);
      await (window as any).photosAPI?.showMessageBox({
        type: 'error',
        title: '清理失败',
        message: '清理缓存时发生错误',
        detail: error instanceof Error ? error.message : '未知错误'
      });
    }
  };

  /**
   * 导出数据
   */
  const exportData = async () => {
    try {
      const result = await (window as any).photosAPI?.showSaveDialog({
        title: '导出数据',
        defaultPath: 'photos-backup.json',
        filters: [
          { name: 'JSON 文件', extensions: ['json'] }
        ]
      });

      if (!result.canceled && result.filePath) {
        // TODO: 实现导出数据的 API
        // await window.photosAPI.exportData(result.filePath);
        
        await (window as any).photosAPI?.showMessageBox({
          type: 'info',
          title: '导出完成',
          message: '数据已成功导出'
        });
      }
    } catch (error) {
      console.error('Failed to export data:', error);
      await (window as any).photosAPI?.showMessageBox({
        type: 'error',
        title: '导出失败',
        message: '导出数据时发生错误',
        detail: error instanceof Error ? error.message : '未知错误'
      });
    }
  };

  /**
   * 导入数据
   */
  const importData = async () => {
    try {
      const result = await (window as any).photosAPI?.showOpenDialog({
        title: '导入数据',
        properties: ['openFile'],
        filters: [
          { name: 'JSON 文件', extensions: ['json'] }
        ]
      });

      if (!result.canceled && result.filePaths.length > 0) {
        const confirmResult = await (window as any).photosAPI?.showMessageBox({
          type: 'warning',
          title: '确认导入',
          message: '确定要导入数据吗？',
          detail: '这将覆盖现有数据，不可撤销',
          buttons: ['取消', '导入'],
          defaultId: 0,
          cancelId: 0
        });

        if (confirmResult.response === 1) {
          // TODO: 实现导入数据的 API
          // await window.photosAPI.importData(result.filePaths[0]);
          
          await (window as any).photosAPI?.showMessageBox({
            type: 'info',
            title: '导入完成',
            message: '数据已成功导入'
          });
        }
      }
    } catch (error) {
      console.error('Failed to import data:', error);
      await (window as any).photosAPI?.showMessageBox({
        type: 'error',
        title: '导入失败',
        message: '导入数据时发生错误',
        detail: error instanceof Error ? error.message : '未知错误'
      });
    }
  };

  /**
   * 返回图库
   */
  const handleBackToLibrary = () => {
    navigate('/');
  };

  /**
   * 更新设置
   */
  const updateSetting = <K extends keyof AppSettings>(key: K, value: AppSettings[K]) => {
    setSettings(prev => ({ ...prev, [key]: value }));
  };

  /**
   * 格式化文件大小
   */
  const formatFileSize = (mb: number): string => {
    if (mb < 1024) {
      return `${mb} MB`;
    }
    return `${(mb / 1024).toFixed(1)} GB`;
  };

  if (loading) {
    return (
      <div className="settings loading">
        <div className="loading-spinner"></div>
        <p>加载设置中...</p>
      </div>
    );
  }

  return (
    <div className="settings">
      {/* 工具栏 */}
      <div className="toolbar">
        <div className="toolbar-left">
          <button className="btn secondary" onClick={handleBackToLibrary}>
            ← 返回图库
          </button>
          <h1 className="page-title">设置</h1>
        </div>
        <div className="toolbar-right">
          <button 
            className="btn secondary"
            onClick={resetSettings}
            disabled={saving}
          >
            重置设置
          </button>
          <button 
            className="btn primary"
            onClick={saveSettings}
            disabled={saving}
          >
            {saving ? '保存中...' : '保存设置'}
          </button>
        </div>
      </div>

      <div className="settings-content">
        {/* 外观设置 */}
        <div className="settings-section">
          <div className="section-header">
            <h2>外观</h2>
            <p>自定义应用程序的外观和显示选项</p>
          </div>
          
          <div className="settings-items">
            <div className="setting-item">
              <div className="setting-info">
                <label>主题</label>
                <span className="setting-description">选择应用程序的主题</span>
              </div>
              <select 
                value={settings.theme}
                onChange={(e) => updateSetting('theme', e.target.value as AppSettings['theme'])}
              >
                <option value="light">浅色</option>
                <option value="dark">深色</option>
                <option value="system">跟随系统</option>
              </select>
            </div>

            <div className="setting-item">
              <div className="setting-info">
                <label>缩略图大小</label>
                <span className="setting-description">设置照片缩略图的显示大小</span>
              </div>
              <select 
                value={settings.thumbnailSize}
                onChange={(e) => updateSetting('thumbnailSize', e.target.value as AppSettings['thumbnailSize'])}
              >
                <option value="small">小</option>
                <option value="medium">中</option>
                <option value="large">大</option>
              </select>
            </div>

            <div className="setting-item">
              <div className="setting-info">
                <label>语言</label>
                <span className="setting-description">选择应用程序的显示语言</span>
              </div>
              <select 
                value={settings.language}
                onChange={(e) => updateSetting('language', e.target.value as AppSettings['language'])}
              >
                <option value="zh-CN">简体中文</option>
                <option value="en-US">English</option>
              </select>
            </div>
          </div>
        </div>

        {/* 导入设置 */}
        <div className="settings-section">
          <div className="section-header">
            <h2>导入</h2>
            <p>配置照片导入的行为和选项</p>
          </div>
          
          <div className="settings-items">
            <div className="setting-item">
              <div className="setting-info">
                <label>自动导入</label>
                <span className="setting-description">监听文件夹变化并自动导入新照片</span>
              </div>
              <label className="switch">
                <input 
                  type="checkbox"
                  checked={settings.autoImport}
                  onChange={(e) => updateSetting('autoImport', e.target.checked)}
                />
                <span className="slider"></span>
              </label>
            </div>

            <div className="setting-item">
              <div className="setting-info">
                <label>重复文件处理</label>
                <span className="setting-description">遇到重复文件时的处理方式</span>
              </div>
              <select 
                value={settings.duplicateHandling}
                onChange={(e) => updateSetting('duplicateHandling', e.target.value as AppSettings['duplicateHandling'])}
              >
                <option value="skip">跳过</option>
                <option value="rename">重命名</option>
                <option value="replace">替换</option>
              </select>
            </div>
          </div>
        </div>

        {/* 性能设置 */}
        <div className="settings-section">
          <div className="section-header">
            <h2>性能</h2>
            <p>调整应用程序的性能和缓存设置</p>
          </div>
          
          <div className="settings-items">
            <div className="setting-item">
              <div className="setting-info">
                <label>缓存大小</label>
                <span className="setting-description">
                  缩略图缓存的最大大小 ({formatFileSize(settings.cacheSize)})
                </span>
              </div>
              <div className="range-input">
                <input 
                  type="range"
                  min="256"
                  max="8192"
                  step="256"
                  value={settings.cacheSize}
                  onChange={(e) => updateSetting('cacheSize', parseInt(e.target.value))}
                />
                <span className="range-value">{formatFileSize(settings.cacheSize)}</span>
              </div>
            </div>

            <div className="setting-item">
              <div className="setting-info">
                <label>清理缓存</label>
                <span className="setting-description">删除所有缩略图缓存以释放空间</span>
              </div>
              <button className="btn secondary" onClick={clearCache}>
                清理缓存
              </button>
            </div>
          </div>
        </div>

        {/* 数据管理 */}
        <div className="settings-section">
          <div className="section-header">
            <h2>数据管理</h2>
            <p>备份和恢复应用程序数据</p>
          </div>
          
          <div className="settings-items">
            <div className="setting-item">
              <div className="setting-info">
                <label>导出数据</label>
                <span className="setting-description">将照片库数据导出为备份文件</span>
              </div>
              <button className="btn secondary" onClick={exportData}>
                导出数据
              </button>
            </div>

            <div className="setting-item">
              <div className="setting-info">
                <label>导入数据</label>
                <span className="setting-description">从备份文件恢复照片库数据</span>
              </div>
              <button className="btn secondary" onClick={importData}>
                导入数据
              </button>
            </div>
          </div>
        </div>

        {/* 关于 */}
        {appInfo && (
          <div className="settings-section">
            <div className="section-header">
              <h2>关于</h2>
              <p>应用程序信息和版本详情</p>
            </div>
            
            <div className="settings-items">
              <div className="setting-item">
                <div className="setting-info">
                  <label>应用名称</label>
                </div>
                <span className="setting-value">{appInfo.name}</span>
              </div>

              <div className="setting-item">
                <div className="setting-info">
                  <label>版本</label>
                </div>
                <span className="setting-value">{appInfo.version}</span>
              </div>

              <div className="setting-item">
                <div className="setting-info">
                  <label>平台</label>
                </div>
                <span className="setting-value">{appInfo.platform} ({appInfo.arch})</span>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}